package com.alibaba.chaosblade.box.common.service;

import com.alibaba.chaosblade.box.common.app.sdk.constants.CacheConstants;
import com.alibaba.chaosblade.box.common.common.domain.user.LoginUser;
import com.alibaba.chaosblade.box.common.common.util.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Set;

/**
 * @description:
 * @author: 李文
 * @create: 2025-09-29 14:15
 **/
@Component
public class TokenService {
    private static final Logger log = LoggerFactory.getLogger(TokenService.class);

    @Autowired
    private RedisTemplate<String, Serializable> chaosRedisTemplate;

    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(String token) {
        LoginUser user = null;
        try {
            if (StringUtils.isNotEmpty(token)) {
                String userkey = JwtUtils.getUserKey(token);
                Serializable serializable = chaosRedisTemplate.opsForValue().get(getTokenKey(userkey));
                if (serializable == null) {
                    return new LoginUser();
                }
                // 检查对象类型并进行相应处理
                if (serializable instanceof LoginUser) {
                    user = (LoginUser) serializable;
                } else {
                    // 如果是JSONObject类型，需要手动转换
                    user = convertJsonObjectToLoginUser(serializable);
                }
                return user;
            }
        } catch (Exception e) {
            log.error("获取用户信息异常'{}'", e.getMessage(), e);
        }
        return user;
    }

    /**
     * 将JSONObject转换为com.alibaba.chaosblade.box.common.common.domain.user.LoginUser
     *
     * @param jsonObject 来自Redis的JSONObject对象
     * @return ChaosBlade系统的LoginUser对象
     */
    private LoginUser convertJsonObjectToLoginUser(Serializable jsonObject) {
        try {
            // 使用FastJSON将JSONObject转换为LoginUser
            String jsonString = com.alibaba.fastjson2.JSON.toJSONString(jsonObject);
            return com.alibaba.fastjson2.JSON.parseObject(jsonString, LoginUser.class);
        } catch (Exception e) {
            log.error("转换JSONObject到LoginUser对象失败: {}", e.getMessage(), e);
            return null;
        }
    }


    private String getTokenKey(String token) {
        return ACCESS_TOKEN + token;
    }
}